﻿using Consul;

namespace MicroserviceDemo
{
    public static class ConsulBuilderExtensions
    {
        public static   IApplicationBuilder RegisterConsul (this IApplicationBuilder app, IConfiguration configuration, IHostApplicationLifetime lifetime=null)
        {
            var ip = configuration["Consul:Ip"];
            var port = configuration["Consul:port"];
            var serviceUrl = configuration["Kestrel:Endpoints:Http:Url"];

           
            //请求注册的 Consul 地址
            var consulClient = new ConsulClient(
                config => 
                {
                    config.Address = new Uri($"http://{ip}:{port}");//consul的地址
                    config.Datacenter = "dc1";
                }
                ) ;

            var serviceId = "orderService-" + Guid.NewGuid();
            AgentServiceRegistration registration = new AgentServiceRegistration();
            registration.Address = serviceUrl.Split(':')[1].Substring(2);
            registration.Port = int.Parse(serviceUrl.Split(':')[2]);
            registration.Name = "orderService";
            registration.ID = serviceId;

            var httpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(10),//服务启动多久后注册
                Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔，或者称为心跳间隔
                HTTP = $"{serviceUrl}/api/health/check",//健康检查地址
                Timeout = TimeSpan.FromSeconds(30)
            };
            registration.Check = httpCheck;

           var result= consulClient.Agent.ServiceRegister(registration).Result;
            if (lifetime!=null)
            {
                lifetime.ApplicationStopped.Register(() => {
                    Console.WriteLine( $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} {serviceId} is stoped!!");
                    consulClient.Agent.ServiceDeregister(serviceId).Wait();
                });
            }

            return app;
        }
    }

 

}
